<?php

namespace app\api\controller\paotui;

use think\Log;
use addons\paotui\library\SnowFlake;
use addons\paotui\service\Config as PaotuiConfig;
use app\admin\model\paotui\PostSocket;
use app\admin\model\paotui\Third;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Validate;
use Yansongda\Pay\Pay;
use app\admin\model\shopro\user\Coupon;

use app\admin\model\shopro\Config as ShoproConfig;
use fast\Http;

/**
 * 快递接口
 */
class Post extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['market_info','send_message','add','send_message_task','testpay','makePaotuiOrder'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = "*";
	
	//masks 记录备忘
	//跑腿订单类型 1跑腿2取件4寄件
	//优惠券类型 0全部 1商城 2取件 3寄件 4跑腿 5外卖
	protected $utypes=[1=>4,2=>2,4=>3];
	protected $otypes=[1=>'跑腿',2=>'取件',4=>'寄件'];
 
    public function _initialize()
    {
        parent::_initialize();
    }

    public function testpay()
    {
		// p(111);
		$posterService = new \addons\paotui\service\Post();
        $posterService->pay_success('4430158686735833106','4200002393202408106282696861');
    }

    /**
     * 快递列表
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(){
        $status = $this->request->post("type",'');
        $page = $this->request->post('page',0);
        $limit = $this->request->post('limit',0);

        $userModel = new \app\admin\model\User();
        $userInfo = $userModel->where(['id'=>$this->auth->id])->find();

        $user_id = $this->auth->id;
        $mobile = $userInfo['mobile'];

        $where = function ($query) use ($user_id,$mobile){
            $query->where(function ($query) use ($mobile){
                $query->where(['to_mobile'=>[['eq',$mobile],['neq','']],'pay_status'=>1]);
            })
                ->whereOr(['user_id'=>$user_id]);
        };
        $postService = new \addons\paotui\service\Post();
        $data = $postService->getPostList($status,$where,$page,$limit,"*","id desc");
        foreach ($data['data'] as &$v){
            $v['from_or_to'] = ($v['user_id'] == $this->auth->id)?'from':'to';
            
            if($v['type'] == 2){
                $station = Db::name('station')->where(['id'=>$v['from_address_id']])->where('deletetime is null')->find();
                $school = Db::name('school')->where(['id'=>$station['school']])->find();
                $v['from_district'] = $school['name'];
                $v['from_poi'] = $station['name'];
                $v['from_address'] = $station['address'];
                $v['from_name'] = $station['name'];
                $v['from_mobile'] = '';
                
                //收件 用户
                $userschool = Db::name('user_school')->where(['id'=>$v['to_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $v['to_district'] = $school['name'];
                $v['to_poi'] = $building['name'];
                $v['to_address'] = $userschool['house_number'];
                $v['to_name'] = $userschool['nickname'];
                $v['to_mobile'] = $userschool['phone'];
                
                //取件码
                $codes  = Db::name('partition_code')->where(['paotui_post_id'=>$v['id']])->select();
                $codearr = [];
                foreach($codes as $kk=>$vv){
                    //取件码分组
                    $partition = Db::name('partition')->where(['id'=>$vv['partition_id']])->find();
                    $station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
                    //整理取件码
                    
                    if($vv['partition_id'] == 0){
                        $data2 = [
                            'partition_name'=>'其他',
                            'code'=>$vv['codes'],
                        ];
                        $codearr[0]['data'][] =  $data2;
                        $codearr[0]['name'] = '其他';
                    }else{
                        $data2 = [
                            'partition_name'=>$partition['name'],
                            'code'=>$vv['codes'],
                        ];
                        $codearr[$station['id']]['data'][] =  $data2;
                        $codearr[$station['id']]['name'] = $station['name'];
                    }
                    
                    
                }
                $v['codearr'] = $codearr;
                
                $ptcode = Db::name('partition_code')->where(['paotui_post_id'=>$v['id'],'status'=>['in','1,2']])->find();
                if($ptcode){
                    $v['codeastatus'] = 1;
                }else{
                    $v['codeastatus'] = 0;
                }
                
            }
            if($v['type'] == 4){
                //收件 用户
                $userschool = Db::name('user_school')->where(['id'=>$v['from_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $v['from_district'] = $school['name'];
                $v['from_poi'] = $building['name'];
                $v['from_address'] = $userschool['house_number'];
                $v['from_name'] = $userschool['nickname'];
                $v['from_mobile'] = $userschool['phone'];
            }
            if($v['type'] == 5){
                //收件 用户
                $userschool = Db::name('user_school')->where(['id'=>$v['to_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $v['from_district'] = $school['name'];
                $v['from_poi'] = $building['name'];
                $v['from_address'] = $userschool['house_number'];
                $v['from_name'] = $userschool['nickname'];
                $v['from_mobile'] = $userschool['phone'];
            }
        }
        $this->success('请求成功',$data);
    }

    /**
     * 快递详情
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info(){
        $order_no = $this->request->post("order_no",'');
        $coupon_id = $this->request->post("coupon_id",0);
        $cpp = $this->request->post("cpp",0);
		

        $postService = new \addons\paotui\service\Post();
        $data = $postService->getInfoByUser($order_no,$this->auth->id);
        // $data = $postService->getInfoByUser(4436088966638211550,1070);
        
// 		p($data);die;
		$utype=$this->utypes[$data['type']];
        
        if($data['type'] == 2 || $data['type'] == 4 || ($data['type']==1 && $data['coupon_price']==0)){ //跑腿在下单时没有写入优惠券的 取件、寄件在支付成功时
			
			if($coupon_id && $cpp==1){
				$coupon=Coupon::with('coupon')->where('id', $coupon_id)->find();
				$coupon_price=$coupon['amount'];
				if($coupon['type']=='discount'){
					$coupon_price=$amount*$coupon['amount'];
				}
				$pay_price=$data['pay_price']-$coupon_price;
				if($pay_price<0)$pay_price=0;
				$data['pay_price']=$pay_price;
				$data['coupon_price']=$coupon_price;
				db('paotui_post')->where('id',$data['id'])->update(['pay_price'=>$pay_price,'coupon_price'=>$coupon_price]);
				db('shopro_user_coupon')->where('id',$coupon_id)->update(['use_type'=>$utype,'use_order_id'=>$data['id'],'use_time'=>time()]);
				
				$muc=db('shopro_user_coupon')->where('ucid',$coupon_id)->find();
				if($muc){
					db('shopro_user_coupon')->update(['id'=>$muc['id'],'isact'=>1,'updatetime'=>time()]);
				}
			}
		}
		if($data['coupon_price']>0){
			$data['coupon']=Coupon::with('coupon')->where('use_type', $utype)->where('use_order_id',$data['id'])->find();
		}else{
			$data['coupon']='';
		}
        if($data['type'] == 2){
			// p($data);
			
			$station = Db::name('station')->where(['id'=>$data['from_address_id']])->where('deletetime is null')->find();
			$school = Db::name('school')->where(['id'=>$station['school']])->find();
			$data['from_district'] = $school['name'];
			$data['from_poi'] = $station['name'];
			$data['from_address'] = $station['address'];
			$data['from_name'] = $station['name'];
			$data['from_mobile'] = '';
			
			//收件 用户
			$userschool = Db::name('user_school')->where(['id'=>$data['to_address_id']])->find();
			$building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
			$data['to_district'] = $school['name'];
			$data['to_poi'] = $building['name'];
			$data['to_address'] = $userschool['house_number'];
			$data['to_name'] = $userschool['nickname'];
			$data['to_mobile'] = $userschool['phone'];
			
			$codes  = Db::name('partition_code')->where(['paotui_post_id'=>$data['id']])->select();
			$codearr = [];
			foreach($codes as $kk=>$vv){
				//取件码分组
				$partition = Db::name('partition')->where(['id'=>$vv['partition_id']])->find();
				$station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
				//整理取件码
				if($vv['partition_id'] == 0){
                    $data2 = [
                        'partition_name'=>'其他',
                        'code'=>$vv['codes'],
                    ];
                    $codearr[0]['data'][] =  $data2;
                    $codearr[0]['name'] = '其他';
                }else{
                    $data2 = [
                        'partition_name'=>$partition['name'],
                        'code'=>$vv['codes'],
                    ];
                    $codearr[$station['id']]['data'][] =  $data2;
                    $codearr[$station['id']]['name'] = $station['name'];
                }
				// $data2 = [
				// 	'partition_name'=>$partition['name'],
				// 	'code'=>$vv['codes'],
				// ];
				
				// $codearr[$station['id']]['data'][] =  $data2;
				// $codearr[$station['id']]['name'] = $station['name'];
			}
			$data['codearr'] = $codearr;
			
			$codesuccess  = Db::name('partition_code')->where(['paotui_post_id'=>$data['id'],'status'=>['in','1,2']])->select();
			foreach($codesuccess as $ck=>&$cv){
				$userposter = Db::name('paotui_poster')->where(['id'=>$cv['take_user_id']])->find();
				$cv['postername'] = $userposter['poster_name'];
				$cv['taketime'] = date('Y-m-d h:i:s',$cv['taketime']);
			}
			$data['codesuccess'] = $codesuccess;
		}
		if($data['type'] == 4){
			//收件 用户
			$userschool = Db::name('user_school')->where(['id'=>$data['from_address_id']])->find();
			$building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
			$school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
			$data['from_district'] = $school['name'];
			$data['from_poi'] = $building['name'];
			$data['from_address'] = $userschool['house_number'];
			$data['from_name'] = $userschool['nickname'];
			$data['from_mobile'] = $userschool['phone'];
		}
		if($data['type'] == 5){
			//收件 用户
			$userschool = Db::name('user_school')->where(['id'=>$data['to_address_id']])->find();
			$building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
			$school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
			$data['from_district'] = $school['name'];
			$data['from_poi'] = $building['name'];
			$data['from_address'] = $userschool['house_number'];
			$data['from_name'] = $userschool['nickname'];
			$data['from_mobile'] = $userschool['phone'];
		}
		$data['issd'] = 0;
		
// 		$type = 0;
// 		if(config('site.firstfree') == 0){
// 		    if(config('site.run_free') != 0){
// 		        $type = 1;
// 		    }  
// 		}else{
// 		    $type=$data['type'];
// 		}
		
		
// 		if($type!=4){
		    
		    
		    
//     		$is1=Db::name('paotui_post')->where(['user_id'=>$this->auth->id,'type'=>$type,'shopro_order_id'=>0])->order('createtime')->find();
    	
//     		if($is1['id']==$data['id']){
//     			$data['issd'] = 1;
//     		}
// 		}
		$is1=Db::name('paotui_post')->where(['user_id'=>$this->auth->id,'shopro_order_id'=>0])->order('createtime')->find();
	
		if($is1['id']==$data['id']){
			$data['issd'] = 1;
		}
		//上班下班时间
		$xbsj=config('site.workoff_time');
		$sbsj=config('site.workon_time');
		$nowdate=date('Y-m-d');
		$tomdate=date('Y-m-d',time()+86400);
		$xbtime=$nowdate.' '.$xbsj;
		$sbtime=$tomdate.' '.$sbsj;
		$sbtimejt=$nowdate.' '.$sbsj;
		$xdsj=date('H:i:s',$data['createtime']);
		$xdtime=$nowdate.' '.$xdsj;
		$isxb=0;
		if($xdtime>$xbtime || $xdtime<$sbtimejt){
			$isxb=1;
		}
		$data['isxb']=$isxb;
		$data['xbtime']=$xbsj;
		$data['sbtime']=$sbsj;
		$yjsd='';
		$nowtime=time();
		$yjtime=$data['createtime']+60*60;
		$dc=$yjtime-$nowtime;
		$dc=$dc/60;
		if($dc<2){
			$yjsd='即将送达';
		}else{
			$yjsd='预计'.round($dc).'分钟后送达';
		}
		$data['yjsd']=$yjsd;
        
        
        $this->success('请求成功',$data);
    }

    /**
     * 公开的快递详情
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function market_info(){
        $order_no = $this->request->post("order_no",'');

        $postService = new \addons\paotui\service\Post();
        $postInfo = $postService->getInfoByMarket($order_no);
        if(empty($postInfo)){
            $this->error('当前快递不存在');
        }

        if($postInfo['user_id'] == $this->auth->id){
            $postInfo['is_owner'] = 1;
        }else{
            $postInfo['is_owner'] = 0;
        }
        $this->success('操作成功',$postInfo);
    }


    /**
     * 获取支付金额
     */
    public function payPrice(){

        $from_address_id = $this->request->post("from_address_id");
        $to_address_id = $this->request->post("to_address_id");
        $type = $this->request->post('type',1);
        $weight = $this->request->post('weight',5);

        $postService = new \addons\paotui\service\Post();
        $return = $postService->getPostDetailPrice($from_address_id,$to_address_id,$this->auth->id,$type,$weight);
        if($return){
            $this->success("请求成功",$return);
        }else{
            $this->error($postService->error);
        }
    }

    /**
     * 获取首单
     */
    public function getMy(){
		$type=$this->request->param('type',1);
		
		
		//全免费
// 		if(config('site.firstfree') == 0){
		    if(config('site.run_free') == 0){
		        return;
		    }   
// 		}
		
		
		
		$is1=Db::name('paotui_post')->where(['user_id'=>$this->auth->id,'type'=>$type])->where('shopro_order_id',0)->find();
		//查看
        if(!$is1){
            $this->success("是");
        }else{
            $this->error('否');
        }
    }

    /**
     * 发快递
     */
    public function add($params=[]){
		if(!$params)$params=$this->request->param();
		Log::write('apijparams:' . json_encode($params) );
		// p($params);
        $isAddFromPay = $params['isAddFromPay']?:0;
        $shopro_order_id = $params['shopro_order_id']?:0;
        
        $user_id = $params['masks_user_id']?:$this->auth->id;
		// p($user_id);
		if(!$user_id)$this->error('请先登录');
		unset($params['token']);
		unset($params['masks_user_id']);
		
		// $this->auth->direct($user_id);
        
        
        $file  = './testApix.txt';
		$content = date('Y-m-d H:i:s')."---订单:".json_encode($user_id)."\n";
		file_put_contents($file, $content,FILE_APPEND);
        
        
	    $id = $params['id']?:0;
        $from_address_id = $params['from_address_id']?:0;
        $to_address_id = $params['to_address_id']?:0;
        $type = $params['type']?:1;
        $goods_type = $params['goods_type']?:1;
        $weight = $params['weight']?:5;
        $b_true_price = $params['b_price']?:0;
        $tips_price = $params['tips_price']?:0;     //小费
        $is_appoints = $params['is_appoints']?:0;
        $appoints_day = $params['appoints_day']?:'';
        $appoints_time = $params['appoints_time']?:'';
        $code = $params['code']?:'';
		$code=trim($code,'、');
        $upstairs = $params['upstairs']?:0;
        $valuable = $params['valuable']?:0;
        $note = $params['note']?:'';
        $remark = $params['remark']?:'';
        $to_address = $params['to_address']?:'';
		
        $coupon_id = $params['coupon_id']?:0;//优惠券

        #判断收发件地址是否正确 start#
        $userAddress = new \addons\paotui\service\UserAddress();
		if($isAddFromPay){
			$fromAddress = $userAddress->getAddressInfo($from_address_id,0);
		}else{
			$fromAddress = $userAddress->getAddressInfo($from_address_id,$user_id);
		}
        // p($fromAddress);die;
        if($type == 1){
            if(empty($fromAddress)){
				if($isAddFromPay){return '请选择正确的发件地址';}else{$this->error('请选择正确的发件地址');}
            }
    
            $toAddress = $userAddress->getAddressInfo($to_address_id,$user_id);
            if(empty($toAddress)){
				if($isAddFromPay){return '请选择正确的收件地址';}else{$this->error('请选择正确的收件地址');}
            }
        }
        #判断收发件地址是否正确 end#

        #获取保价金额 start#
        if($b_true_price){
            $b_price = $b_true_price;
        }else{
            $b_price = 0;
        }
        #获取保价金额 end#
		
		// 20240816 masks 新增跑腿 用户有没完成且没支付的订单的话 再下单自动追加到这个订单
		// 20240819 masks 只要填了价格就需要支付了 群里确定的
		if(!$id && $type==2){
			// 在没取完订单之前下单都需要追加到之前的订单里，只有取完、处理异常完订单状态变成5了才需要提示去支付之前的单，在此之前都是提示
			$orderCanAppend = Db::name('paotui_post')->where(['user_id'=>$user_id,'status'=>2,'pay_status'=>0,'type'=>2,'is_delete'=>0])->order('createtime desc')->find();//,'total_price'=>'0.00'
			if($orderCanAppend){
				$id=$orderCanAppend['id'];
			}
		}


		if(!$id){
			$order_code = SnowFlake::generateId();  //获取订单编号

			$data['order_no'] = $order_code;        //订单号
			$data['user_id'] = $user_id;
			$data['type'] = $type;
			if($type == 1){
				$data['from_address_id'] = $fromAddress['id'];
				$data['from_province'] = $fromAddress['province'];
				$data['from_city'] = $fromAddress['city'];
				$data['from_district'] = $fromAddress['district'];
				$data['from_name'] = $fromAddress['name'];
				$data['from_mobile'] = $fromAddress['mobile'];
				$data['from_address'] = str_replace(["\t", "\r\n", "\r", "\n", " "], '', $fromAddress['address']);
				$data['from_poi'] = $fromAddress['poi'];
				$data['from_lng'] = $fromAddress['lng'];
				$data['from_lat'] = $fromAddress['lat'];
				$data['from_first_code'] = empty($fromCode['first_code'])?'':$fromCode['first_code'];
				$data['from_second_code'] = empty($fromCode['second_code'])?'':$fromCode['second_code'];
				$data['to_address_id'] = $toAddress['id'];
				$data['to_province'] = $toAddress['province'];
				$data['to_city'] = $toAddress['city'];
				$data['to_district'] = $toAddress['district'];
				$data['to_name'] = $toAddress['name'];
				$data['to_mobile'] = $toAddress['mobile'];
				$data['to_address'] = str_replace(["\t", "\r\n", "\r", "\n", " "], '', $toAddress['address']);
				$data['to_poi'] = $toAddress['poi'];
				$data['to_lng'] = $toAddress['lng'];
				$data['to_lat'] = $toAddress['lat'];
				$data['school_name'] = $toAddress['school_name'];
				$data['build_name'] = $toAddress['build_name'];
				$data['to_first_code'] = empty($toCode['first_code'])?'':$toCode['first_code'];
				$data['to_second_code'] = empty($toCode['second_code'])?'':$toCode['second_code'];
				
				//获取最近的接单学校
				$allschool = Db::name('school')->select();
				$data['school'] = '';
				$distance = 0;
				foreach($allschool as $ak=>$av){
					$scdistance = abs($av['lng']-$fromAddress['lng']) + abs($av['lat']-$fromAddress['lat']);
					if($ak == 0){
						$distance = $scdistance;
						$data['school'] = $av['id'];
					}else{
						if($distance>$scdistance){
							$distance = $scdistance;
							$data['school'] = $av['id'];
						}
					}
				}
				
			}
			else{
				$data['from_address_id'] = $from_address_id;
				$data['to_address'] = $to_address;
				$data['to_address_id'] = $to_address_id;
			}
			
			$data['goods_type'] = $goods_type;
			$data['weight'] = $weight;
			$data['b_price'] = $b_price;    //保价支付金额
			$data['b_true_price'] = $b_true_price;      //物品价格
			$data['tips_price'] = $tips_price;
			$data['note'] = $note;
			$data['nextsendtime'] = time();
			
			$data['is_appoints'] = $is_appoints;
			
			$data['code'] = $code;
        }else{
			$postModel = new \app\admin\model\paotui\Post();
			$data=$postModel->get($id);
			$codey=$data['code'];
			if($code){
				$codex=trim($codey,'、').'、'.trim($code,'、');
			}else{
				$codex=$codey;
			}
			$data['code'] = $codex;
		}
		
		
        $data['remark'] = $remark;
        $data['appoints_day'] = $appoints_day;
        $data['appoints_time'] = $appoints_time;
        
       
        $data['upstairs'] = $upstairs;
        $data['valuable'] = $valuable;   
        
        $total_price = 0;
        $total_price = bcadd($total_price,$data['upstairs'],2);          //上楼
        $total_price = bcadd($total_price,$data['valuable'],2);          //加急
        
        $pay_price = 0;
        $pay_price = bcadd($pay_price,$data['upstairs'],2);          //上楼
        $pay_price = bcadd($pay_price,$data['valuable'],2);          //加急
        $data['pay_price'] = $pay_price;      //实际支付价格
        
        $data['total_price'] = $total_price;    
		
        if($type == 1){
			$data['shopro_order_id']=$shopro_order_id;
                #地址验证 start#
                // if(!\addons\paotui\service\UserAddress::checkCity($data['from_city'])){
                //     $this->error("当前选择位置不在运营范围内！");
                // }
        
                // if(!\addons\paotui\service\UserAddress::checkCity($data['to_city'])){
                //     $this->error("当前选择位置不在运营范围内！");
                // }
            
            #预约 start#
    
           
    
            if($is_appoints){
                if(empty($data['appoints_day']) || empty($data['appoints_time'])){
					if($isAddFromPay){return '请选择预约时间';}else{$this->error('请选择预约时间');}
                }
            }else{
                unset($data['appoints_day']);
                unset($data['appoints_time']);
            }
            #预约 end#
        
            #获取收发件经纬度之间的距离 米 start#
            
            $postService = new \addons\paotui\service\Post();
			if($isAddFromPay){
				$commonPrice = $postService->getPostDetailPrice($from_address_id,$to_address_id,$user_id,$type,$weight,$isAddFromPay,11);
			}else{
				$commonPrice = $postService->getPostDetailPrice($from_address_id,$to_address_id,$user_id,$type,$weight,$isAddFromPay);
			}
            if(!$commonPrice){
				if($isAddFromPay){return $postService->error;}else{$this->error($postService->error);}
            }
    
            $data['distance'] = $commonPrice['distance'];
            $data['general_price'] = $commonPrice['general_price'];
            $data['over_distance'] = $commonPrice['over_distance'];
            $data['over_distance_price'] = $commonPrice['over_distance_price'];
            //2024.9.25 晚 ，先取消掉超重费用和距离费
            // $data['over_weight_price'] = $commonPrice['over_weight_price'];
            // $data['over_weight'] = $commonPrice['over_weight'];
            // $data['extra_price'] = $commonPrice['extra_price'];
            
            $data['over_weight_price'] = 0;
            $data['over_weight'] = 0;
            $data['extra_price'] = 0;
            
            
            
            
            $data['extra_node'] = $commonPrice['extra_node'];
    
            $total_price = bcadd($data['general_price'],$data['b_price'],2);    //基础费用+保价费用
            $total_price = bcadd($total_price,$data['tips_price'],2);           //小费
            $total_price = bcadd($total_price,$data['over_distance_price'],2);  //超出里程费用
            $total_price = bcadd($total_price,$data['over_weight_price'],2);    //超出重量费用
            $total_price = bcadd($total_price,$data['extra_price'],2);          //溢价
			
			
            
               //原始价格
    
            if(isset($commonPrice['discount_price'])){
                //如果有折扣价，计算折扣价,折扣价格中包含超重和超距离费用
                $pay_price = bcadd($commonPrice['discount_price'],$data['b_price'],2);    //折扣价格+保价费用
                $pay_price = bcadd($pay_price,$data['tips_price'],2);           //小费
                $pay_price = bcadd($pay_price,$data['extra_price'],2);          //溢价
            }else{
                $pay_price = bcadd($data['general_price'],$data['b_price'],2);    //基础费用+保价费用
                $pay_price = bcadd($pay_price,$data['tips_price'],2);           //小费
                $pay_price = bcadd($pay_price,$data['over_distance_price'],2);  //超出里程费用
                $pay_price = bcadd($pay_price,$data['over_weight_price'],2);    //超出重量费用
                $pay_price = bcadd($pay_price,$data['extra_price'],2);          //溢价
            }
            
			
			#获取优惠券 start#
			$coupon_price=0;
			if($coupon_id){
				$coupon=Coupon::with('coupon')->where('id', $coupon_id)->find();
				if($coupon['coupon']['use_type']>0 && $coupon['coupon']['use_type']!=4){
					if($isAddFromPay){return '优惠券不可用于该类型';}else{$this->error('优惠券不可用于该类型');}
				}
				if($coupon['isact']==0){
					if($isAddFromPay){return '优惠券未激活';}else{$this->error('优惠券未激活');}
				}
				$coupon_price=$coupon['amount'];
				if($coupon['type']=='discount'){
					$coupon_price=$amount*$coupon['amount'];
				}
				// p($coupon_price);
				// p($data);
				$pay_price=$pay_price-$coupon_price;
				if($pay_price<0){
					if($isAddFromPay){return '支付金额有误';}else{$this->error('支付金额有误');}
				}
				$data['coupon_price']=$coupon_price;
			}
			$data['pay_price']=$pay_price;
			$data['total_price']=$total_price;
			#获取优惠券 end#
           
            #获取佣金 start#
            if(isset($commonPrice['discount_price'])){
                $allow_brokerage_price = bcadd($commonPrice['discount_price'],$data['tips_price'],2);           //小费
                $allow_brokerage_price = bcadd($allow_brokerage_price,$data['extra_price'],2);          //溢价
            }else{
                $allow_brokerage_price = bcadd($data['general_price'],$data['tips_price'],2);           //小费
                $allow_brokerage_price = bcadd($allow_brokerage_price,$data['over_distance_price'],2);  //超出里程费用
                $allow_brokerage_price = bcadd($allow_brokerage_price,$data['over_weight_price'],2);    //超出重量费用
                $allow_brokerage_price = bcadd($allow_brokerage_price,$data['extra_price'],2);          //溢价
            }
			$allow_brokerage_price=$allow_brokerage_price-$coupon_price;
    
			//20240813 masks 新增扣除其他费用
			$allow_brokerage_price=getqsmoney($user_id,$allow_brokerage_price);
			
            $data['brokerage']=$allow_brokerage_price;
            
            #获取佣金 end#
			
        
            #获取收发件经纬度之间的距离 米 end#
            $msg = [
                'from_address_id.require' => '请选择发件地址',
                'to_address_id.require' => '请选择收件地址',
                'goods_type.require' => '请选择物品类型',
                'weight.require' => '请填写物品重量'
            ];
    
            $rule = [
                'from_address_id'  => 'require',
                'to_address_id'  => 'require',
                'goods_type'=>'require',
                'weight'=>'require',
            ];
            
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
				if($isAddFromPay){return __($validate->getError());}else{$this->error(__($validate->getError()), null,[]);}
            }
            
            //直接支付成功
            if($isAddFromPay){
                $data['status'] = 2;
                $data['pay_status'] = 1;
                $data['paytime'] = time();
            }
            $isfree=config('site.run_free');
    		if($isfree){
    			$is1=Db::name('paotui_post')->where(['user_id'=>$user_id,'type'=>1])->where('shopro_order_id',0)->find();
    			if(!$is1){
    				$data['pay_price']=0;
    			}
    		}
            
        }else{
            $data['status'] =0;
        }
        
        $from_school = $params['from_school']?:0;
        if($type == 4){
            $data['status'] =2;
            $data['user_school_id'] = $from_school;
        }
        if($type == 5){
            $data['status'] =2;
            $data['cloth'] = $params['washnum']?:0;
            $data['user_school_id'] = $from_school;
        }
        if($type == 4){
            $school = Db::name('user_school')->where(['id'=>$data['from_address_id']])->find();
            $data['school'] =$school['school_id'];
        }
        if($type == 5){
            $school = Db::name('user_school')->where(['id'=>$data['to_address_id']])->find();
            $data['school'] =$school['school_id'];
            //生成洗衣唛
            $today = date('Ymd',time());
            $tdstart = strtotime(date('Y-m-d',time()));
            $tdend = $tdstart+86400;
            $tdcloth = Db::name('paotui_post')->where(['createtime'=>['between',[$tdstart,$tdend]],'type'=>5])->count();
            $data['clothcode'] = $today.$tdcloth;
            
        }
        if($type == 2){
            $data['status'] =2;
            $school = Db::name('user_school')->where(['id'=>$data['to_address_id']])->find();
            $data['school'] =$school['school_id'];
        }
        
        $postService = new \addons\paotui\service\Post();
		
		//masks 首单判断
		$isfree=config('site.run_free');
		if($isfree){
			$is1=Db::name('paotui_post')->where(['user_id'=>$user_id,'type'=>$type])->find();
			if(!$is1){
				$data['pay_price']=0;
			}
		}
		$vipend=$this->auth->vipend;
		$ptmoney=0;
		if($vipend && $vipend>date('Y-m-d')){
			$configs = ShoproConfig::getConfigs('shop.vip', false);
			$amounts=$configs['amounts'];
			$ptmoney=$amounts[0]['ptmoney']?:0;
		}
        
        if($code){
            // $code2 = [];
            // foreach($code as $cok=>$cov){
            //     if($cov){
            //       $code2[] =  $cov;
            //     }
            // }
            // $code = $code2;
            //判断之前有没有没支付的订单
			//20240815 判断一下 非追加的还是按以前的判断，追加订单判断是否是当前订单
			if($id){
				$ordernopay = Db::name('paotui_post')->where(['user_id'=>$user_id,'status'=>5,'pay_status'=>0,'type'=>2,'is_delete'=>0])->find();
			}else{
				// $ordernopay = Db::name('paotui_post')->where(['user_id'=>$user_id,'pay_status'=>0,'type'=>2,'is_delete'=>0])->find();
				$ordernopay = Db::name('paotui_post')->where(['user_id'=>$user_id,'status'=>5,'pay_status'=>0,'type'=>2,'is_delete'=>0])->find();
				
			}
			// p($id);
			// p($ordernopay);
			// die;
            if($ordernopay){
				if($isAddFromPay){return '您有订单未支付，请在支付后提交新订单';}else{$this->error('您有订单未支付，请在支付后提交新订单',$ordernopay['order_no']);}
            }
            $code_arr = explode('、',$code);
			$code_arr = array_filter($code_arr);
			$date7=strtotime(date('Y-m-d'))-86400*7;
			$codesjk=Db::name('partition_code')->where('codes','in',$code_arr)->where('createtime','egt',$date7)->where('canceltime',0)->select();
		
			$toaddressphone =Db::name('user_school')->where('id',$data['to_address_id'])->find(); 
			if($codesjk){
			    $codesjkstr = '';
			    foreach($codesjk as $ck1=>$cv1){
			        $cx = 0;
			        $cpost = Db::name('paotui_post')->where('id',$cv1['paotui_post_id'])->find();
			        $cuser = Db::name('user_school')->where('id',$cpost['to_address_id'])->find();
			        //判断用户和手机号是否和用户的一致
			        if($cuser['user_id'] == $user_id){
			             $cx = 1;
			        }
			        //判断手机号
			        if($cuser['phone'] == $toaddressphone['phone']){
			            $cx = 1;
			        }
			        if($cx == 1){
			            if($codesjkstr){
			                $codesjkstr .= '、'.$cv1['codes'];
			            }else{
			                $codesjkstr = $cv1['codes'];
			            }
			        }
			    }
				
				if($isAddFromPay){return '取件码：'.$codesjkstr.' 在一周内已被使用，请删除重试';}else{$this->error('取件码：'.$codesjkstr.' 在一周内已被使用，请删除重试');}
			}
            //如果有code 根据code判断取件码
            $newcodearr = [];
            foreach($code_arr as $k=>$v){
                $code_top = substr($v,0,1);
                if($code_top == 'J'||$code_top == 'D'||$code_top == 'K'||$code_top == 'Y'||$code_top == 'T'){
                    //为京东快递
                    if(!$newcodearr['jd']){
                        $newcodearr['jd'] = $v;
                    }else{
                        $newcodearr['jd'] .= '、'.$v;
                    }
                   
                }else if($code_top == 'A'||$code_top == 'B'){
                    //极兔快递
                    if(!$newcodearr['jt']){
                        $newcodearr['jt'] = $v;
                    }else{
                        $newcodearr['jt'] .= '、'.$v;
                    }
                }else if($code_top == 'Z'){
                    //中通//兔喜
                    if(!$newcodearr['zt']){
                        $newcodearr['zt'] = $v;
                    }else{
                        $newcodearr['zt'] .= '、'.$v;
                    }
                }else if($code_top == 'S'){
                    //顺丰
                    if(!$newcodearr['sf']){
                        $newcodearr['sf'] = $v;
                    }else{
                        $newcodearr['sf'] .= '、'.$v;
                    }
                }else if(0<$code_top&&$code_top<10){
                    //菜鸟
                    if(!$newcodearr['cn']){
                        $newcodearr['cn'] = $v;
                    }else{
                        $newcodearr['cn'] .= '、'.$v;
                    }
                }else{
                    if(!$newcodearr['other']){
                        $newcodearr['other'] = $v;
                    }else{
                        $newcodearr['other'] .= '、'.$v;
                    }
                    // $this->error('取件码'.$v.'错误');
                }
            }
            if($newcodearr['jd']){
                $kdz1 = Db::name('station')->where(['school'=>$from_school,'type'=>1])->where('deletetime is null')->find();
                
                $data['from_address_id']  = $kdz1['id'];
                if(!$kdz1){
					if($isAddFromPay){return '没有对应的快递站';}else{$this->error('没有对应的快递站');}
                }
                $partition = Db::name('partition')->where(['station_id'=>$kdz1['id']])->select();
                
                $jdcode = explode('、',$newcodearr['jd']);
                
                foreach($partition as $k2=>$v2){
                   
                    foreach($jdcode as $kk=>$vv){
                        
                        if(strstr($vv,$v2['name'])){
                            //判断重复
                            $iscf = Db::name('partition_code')->where('canceltime',0)->where(['codes'=>$vv,'status'=>0])->find();
                            if($iscf){
								if($isAddFromPay){return '取件码重复';}else{$this->error('取件码重复');}
                            }
                            // if(!$codedata[$v2['id']]){
                                $codedata[$v2['id']][] = $vv;
                            // }else{
                            //     $codedata[$v2['id']] .= '、'.$vv;
                            // }
                             
                            unset($jdcode[$kk]);
                        }
                    }
                }
                if($jdcode){
                    //没有快递柜，不给入库
					if($isAddFromPay){return '该驿站没有对应的快递柜，请联系管理员';}else{$this->error('该驿站没有对应的快递柜，请联系管理员');}
                }
                
                
                // $result = $postService->addPost($data);
            }
            
            if($newcodearr['jt']){
                $kdz2 = Db::name('station')->where(['school'=>$from_school,'type'=>2])->where('deletetime is null')->find();
                $data['from_address_id']  = $kdz2['id'];
                if(!$kdz2){
					if($isAddFromPay){return '没有对应的快递站';}else{$this->error('没有对应的快递站');}
                }
                $partition = Db::name('partition')->where(['station_id'=>$kdz2['id']])->select();
                $jtcode = explode('、',$newcodearr['jt']);
                foreach($partition as $k2=>$v2){
                    foreach($jtcode as $kk=>$vv){
                        if(strstr($vv,$v2['name'])){
                            $iscf = Db::name('partition_code')->where('canceltime',0)->where(['codes'=>$vv,'status'=>0])->find();
                            if($iscf){
								if($isAddFromPay){return '取件码重复';}else{$this->error('取件码重复');}
                            }
                            // if(!$codedata[$v2['id']]){
                                $codedata[$v2['id']][] = $vv;
                            // }else{
                            //     $codedata[$v2['id']] .= '、'.$vv;
                            // }
                            unset($jtcode[$kk]);
                        }
                    }
                }
               
                if($jtcode){
					if($isAddFromPay){return '该驿站没有对应的快递柜，请联系管理员';}else{$this->error('该驿站没有对应的快递柜，请联系管理员');}
                }
                
                // $result = $postService->addPost($data);
            }
            if($newcodearr['zt']){
                $kdz3 = Db::name('station')->where(['school'=>$from_school,'type'=>3])->where('deletetime is null')->find();
                $data['from_address_id']  = $kdz3['id'];
                if(!$kdz3){
					if($isAddFromPay){return '没有对应的快递站';}else{$this->error('没有对应的快递站');}
                }
                $partition = Db::name('partition')->where(['station_id'=>$kdz3['id']])->select();
                $ztcode = explode('、',$newcodearr['zt']);
                foreach($partition as $k2=>$v2){
                    foreach($ztcode as $kk=>$vv){
                        if(strstr($vv,$v2['name'])){
                            $iscf = Db::name('partition_code')->where('canceltime',0)->where(['codes'=>$vv,'status'=>0])->find();
                            if($iscf){
								if($isAddFromPay){return '取件码重复';}else{$this->error('取件码重复');}
                            }
                            $codedata[$v2['id']][] = $vv;
                            // if(!$codedata[$v2['id']]){
                            //     $codedata[$v2['id']] .= $vv;
                            // }else{
                            //     $codedata[$v2['id']] .= '、'.$vv;
                            // }
                            unset($ztcode[$kk]);
                        }
                    }
                }
                
                if($ztcode){
					if($isAddFromPay){return '该驿站没有对应的快递柜，请联系管理员';}else{$this->error('该驿站没有对应的快递柜，请联系管理员');}
                }
                // $result = $postService->addPost($data);
            }
            if($newcodearr['sf']){
                $kdz4 = Db::name('station')->where(['school'=>$from_school,'type'=>4])->where('deletetime is null')->find();
                if(!$kdz4){
					if($isAddFromPay){return '没有对应的快递站';}else{$this->error('没有对应的快递站');}
                }
                $data['from_address_id']  = $kdz4['id'];
                $partition = Db::name('partition')->where(['station_id'=>$kdz4['id']])->select();
                $sfcode = explode('、',$newcodearr['sf']);
                foreach($partition as $k2=>$v2){
                    foreach($sfcode as $kk=>$vv){
                        
                        if(strstr($vv,$v2['name'])){
                            $iscf = Db::name('partition_code')->where('canceltime',0)->where(['codes'=>$vv,'status'=>0])->find();
                            if($iscf){
								if($isAddFromPay){return '取件码重复';}else{$this->error('取件码重复');}
                            }
                            $codedata[$v2['id']][] = $vv;
                            // if(!$codedata[$v2['id']]){
                            //     $codedata[$v2['id']] .= $vv;
                            // }else{
                            //     $codedata[$v2['id']] .= '、'.$vv;
                            // }
                            unset($sfcode[$kk]);
                        }
                    }
                }
                
                if($sfcode){
					if($isAddFromPay){return '该驿站没有对应的快递柜，请联系管理员';}else{$this->error('该驿站没有对应的快递柜，请联系管理员');}
                }
                // $result = $postService->addPost($data);
            }
            if($newcodearr['cn']){
                $kdz5 = Db::name('station')->where(['school'=>$from_school,'type'=>5])->where('deletetime is null')->find();
                if(!$kdz5){
					if($isAddFromPay){return '没有对应的快递站';}else{$this->error('没有对应的快递站');}
                }
                $data['from_address_id']  = $kdz5['id'];
                $partition = Db::name('partition')->where(['station_id'=>$kdz5['id']])->select();
                $cncode = explode('、',$newcodearr['cn']);
                foreach($partition as $k2=>$v2){
                    foreach($cncode as $kk=>$vv){
                        if(strstr($vv,$v2['name'])){
                            $iscf = Db::name('partition_code')->where('canceltime',0)->where(['codes'=>$vv,'status'=>0])->find();
                            if($iscf){
								if($isAddFromPay){return '取件码重复';}else{$this->error('取件码重复');}
                            }
                            $codedata[$v2['id']][] = $vv;
                            // if(!$codedata[$v2['id']]){
                            //     $codedata[$v2['id']] .= $vv;
                            // }else{
                            //     $codedata[$v2['id']] .= '、'.$vv;
                            // }
                            unset($cncode[$kk]);
                        }
                    }
                }
                if($cncode){
					if($isAddFromPay){return '该驿站没有对应的快递柜，请联系管理员';}else{$this->error('该驿站没有对应的快递柜，请联系管理员');}
                }
                // $result = $postService->addPost($data);
            }
            if($newcodearr['other']){
                
                $data['from_address_id']  = '0';
                $othercode = explode('、',$newcodearr['other']);
               
                foreach($othercode as $kk=>$vv){
                    $iscf = Db::name('partition_code')->where('canceltime',0)->where(['codes'=>$vv,'status'=>0])->find();
                    if($iscf){
						if($isAddFromPay){return '取件码重复';}else{$this->error('取件码重复');}
                    }
                    $codedata['other'][] = $vv;
                    unset($othercode[$kk]);
                }
                
                
                // $result = $postService->addPost($data);
            }
            // p(1);
			// p($data);die;
			
			if($id){
				$result = $postService->savePost($data);
			}else{
				$result = $postService->addPost($data);
			}
        
            if($result){
				$pdata = [
					'paotui_post_id'=>$result['id'],
					'createtime'=>time(),
					'updatetime'=>time(),
					'school'=>$data['school'],
					'canceltime'=>0
				];
				if($ptmoney){
					$pdata['price']=$ptmoney;
				}
                if($kdz1){
                  
                    //京东
                    //获取京东的partition
                    $partition = Db::name('partition')->where(['station_id'=>$kdz1['id']])->select();
                    $jdcode = explode('、',$newcodearr['jd']);
                    $codedata = [];
                    
                    foreach($partition as $k=>$v){
                        foreach($jdcode as $kk=>$vv){
                            if(strstr($vv,$v['name'])){
                                $codedata[$v['id']][] = $vv;
                                // if(!$codedata[$v['id']]){
                                //     $codedata[$v['id']] .= $vv;
                                // }else{
                                //     $codedata[$v['id']] .= '、'.$vv;
                                // }
                                unset($jdcode[$kk]);
                            }
                        }
                    }
                    
                    if($codedata){
                       
                        foreach($codedata as $ck=>$cv){
                            foreach($cv as $ck1=>$ck2){
                                $pdata['partition_id'] = $ck;
                                $pdata['codes'] = $ck2;
                                $jdinsert = Db::name('partition_code')->insert($pdata);
                            }
                        }
                    }
                    
                }
                
                if($kdz2){
                    //获取京东的partition
                    //极兔快递
                    $partition = Db::name('partition')->where(['station_id'=>$kdz2['id']])->select();
                    $jtcode = explode('、',$newcodearr['jt']);
                    $codedata = [];
                    
                    foreach($partition as $k=>$v){
                        foreach($jtcode as $kk=>$vv){
                            if(strstr($vv,$v['name'])){
                                $codedata[$v['id']][] = $vv;
                                // if(!$codedata[$v['id']]){
                                //     $codedata[$v['id']] .= $vv;
                                // }else{
                                //     $codedata[$v['id']] .= '、'.$vv;
                                // }
                                unset($jtcode[$kk]);
                            }
                        }
                    }
                     
                    if($codedata){
                        foreach($codedata as $ck=>$cv){
                            foreach($cv as $ck1=>$ck2){
                                $pdata['partition_id'] = $ck;
                                $pdata['codes'] = $ck2;
                                $jdinsert = Db::name('partition_code')->insert($pdata);
                            }
                        }
                    }
                    
                }
                if($kdz3){
                    //中通//兔喜
                    //获取京东的partition
                    $partition = Db::name('partition')->where(['station_id'=>$kdz3['id']])->select();
                    $ztcode = explode('、',$newcodearr['zt']);
                    $codedata = [];
                    
                    foreach($partition as $k=>$v){
                        foreach($ztcode as $kk=>$vv){
                            if(strstr($vv,$v['name'])){
                                $codedata[$v['id']][] = $vv;
                                // if(!$codedata[$v['id']]){
                                //     $codedata[$v['id']] .= $vv;
                                // }else{
                                //     $codedata[$v['id']] .= '、'.$vv;
                                // }
                                unset($ztcode[$kk]);
                            }
                        }
                    }
                    
                    if($codedata){
                        foreach($codedata as $ck=>$cv){
                            foreach($cv as $ck1=>$ck2){
                                $pdata['partition_id'] = $ck;
                                $pdata['codes'] = $ck2;
                                $jdinsert = Db::name('partition_code')->insert($pdata);
                            }
                        }
                    }
                    
                }
                if($kdz4){
                    //顺丰
                    //获取京东的partition
                    $partition = Db::name('partition')->where(['station_id'=>$kdz4['id']])->select();
                    $sfcode = explode('、',$newcodearr['sf']);
                    $codedata = [];
                    
                    foreach($partition as $k=>$v){
                        foreach($sfcode as $kk=>$vv){
                            if(strstr($vv,$v['name'])){
                                $codedata[$v['id']][] = $vv;
                                // if(!$codedata[$v['id']]){
                                //     $codedata[$v['id']] .= $vv;
                                // }else{
                                //     $codedata[$v['id']] .= '、'.$vv;
                                // }
                                unset($sfcode[$kk]);
                            }
                        }
                    }
					
                    if($codedata){
                        foreach($codedata as $ck=>$cv){
                            foreach($cv as $ck1=>$ck2){
                                $pdata['partition_id'] = $ck;
                                $pdata['codes'] = $ck2;
                                $jdinsert = Db::name('partition_code')->insert($pdata);
                            }
                        }
                    }
                    
                }
                if($kdz5){
                    //菜鸟
                    //获取京东的partition
                    $partition = Db::name('partition')->where(['station_id'=>$kdz5['id']])->select();
                    $cncode = explode('、',$newcodearr['cn']);
                    $codedata = [];
                    
                    foreach($partition as $k=>$v){
                        foreach($cncode as $kk=>$vv){
                            if(strstr($vv,$v['name'])){
                                $codedata[$v['id']][] = $vv;
                                unset($cncode[$kk]);
                            }
                        }
                    }
                    
                    if($codedata){
                        foreach($codedata as $ck=>$cv){
                            foreach($cv as $ck1=>$ck2){
                                $pdata['partition_id'] = $ck;
                                $pdata['codes'] = $ck2;
                                $jdinsert = Db::name('partition_code')->insert($pdata);
                            }
                        }
                    }
                    
                }
                if($newcodearr['other']){
                    $othercode = explode('、',$newcodearr['other']);
                    foreach($othercode as $ck=>$cv){
                        $pdata['partition_id'] = 0;
                        $pdata['codes'] = $cv;
                        $otherinsert = Db::name('partition_code')->insert($pdata);
                    }
                }
            }
           
            //提交
            //如果可以，需要上传多个订单，先判断是否存在驿站
            if($result){
				if($type==1 && $coupon_id){ //两处处理优惠券使用
					db('shopro_user_coupon')->where('id',$coupon_id)->update(['use_type'=>4,'use_order_id'=>$result->id,'use_time'=>time()]);
					
					$muc=db('shopro_user_coupon')->where('ucid',$coupon_id)->find();
					if($muc){
						db('shopro_user_coupon')->update(['id'=>$muc['id'],'isact'=>1,'updatetime'=>time()]);
					}
				}
				
				//订单发送短信
				if($data['valuable']>0){
				    $this->send_message((string)$result->order_no);
				}
				//写入合并订单表
				$goods_name=$this->otypes[$type].'-'.$appoints_day;
				$total_money=$ptmoney;
				
				$mergeorder = [
					'tb_name'=>'paotui_post',
					'type'=>$type,
					'user_id'=>$user_id,
					'order_ids'=>$result->id,
					'goods_name'=>$goods_name,
					'total_money'=>$total_money,
					'status'=>0,
					'remark'=>$remark,
					'createtime'=>time(),
				];
				if($shopro_order_id){
				   $mergeorder['is_follow'] = 1; 
				}
				
				inMergeOrder($mergeorder);
				
				// 写入抢单信息
				$dispatch_mode = PaotuiConfig::get('dispatch_mode');
				$datap =[
					'post_id'=>$result->id,
					'type'=>$dispatch_mode,
					'type1'=>$type,
					'next_send_time'=>time(),
					'send_num'=>0,
					'send_status'=>0,
					'createtime'=>time()
				];
				
				if($datap){
					$postSocketModel = new PostSocket();
					$postSocketModel->insert($datap);
				}
				
				if($isAddFromPay){return '提交成功';}else{$this->success('提交成功',['order_no'=>(string)$result->order_no]);}
                
            }else{
				if($isAddFromPay){return '提交失败';}else{$this->error('提交失败');}
            }
        }else{
			// p(2);
			// p($data);die;
            if($result = $postService->addPost($data)){
				
				if($type==1 && $coupon_id){ //两处处理优惠券使用
					db('shopro_user_coupon')->where('id',$coupon_id)->update(['use_type'=>4,'use_order_id'=>$result->id,'use_time'=>time()]);
					
					$muc=db('shopro_user_coupon')->where('ucid',$coupon_id)->find();
					if($muc){
						db('shopro_user_coupon')->update(['id'=>$muc['id'],'isact'=>1,'updatetime'=>time()]);
					}
				}
				if($type == 4&&$result){
				    $this->send_message((string)$result->order_no);
				}
				//写入合并订单表
				$goods_name=$this->otypes[$type].'-'.$appoints_day;
				$total_money=$ptmoney;
				
				
				$mergeorder = [
					'tb_name'=>'paotui_post',
					'type'=>$type,
					'user_id'=>$user_id,
					'order_ids'=>$result->id,
					'goods_name'=>$goods_name,
					'total_money'=>$total_money,
					'status'=>0,
					'remark'=>$remark,
					'createtime'=>time(),
				];
				if($shopro_order_id){
				   $mergeorder['is_follow'] = 1; 
				}
				
				inMergeOrder($mergeorder);
				
				
				
				// 写入抢单信息
				$dispatch_mode = PaotuiConfig::get('dispatch_mode');
				$datap=[
					'post_id'=>$result->id,
					'type'=>$dispatch_mode,
					'type1'=>$type,
					'next_send_time'=>time(),
					'send_num'=>0,
					'send_status'=>0,
					'createtime'=>time()
				];
				
				if($datap){
					$postSocketModel = new PostSocket();
					$postSocketModel->insert($datap);
				}
                
				if($isAddFromPay){return '提交成功';}else{$this->success('提交成功',['order_no'=>(string)$result->order_no]);}
            }else{
				if($isAddFromPay){return '提交失败';}else{$this->error('提交失败');}
            }
        }
    }
    public function getnopayorder(){
        $ordernopay = Db::name('paotui_post')->where(['user_id'=>$this->auth->id,'status'=>5,'pay_status'=>0,'type'=>2,'is_delete'=>0])->find();//,2
        if($ordernopay){
            $this->success('您有订单未支付，请在支付后提交新订单',$ordernopay['order_no']);
        }else{
			$this->error('没有未支付订单');
		}
    } 
    /**
     * 支付订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pay(){

		// $this->error('微信授权获取失败，请至我的中绑定微信'); //仅测试用
		// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----支付2：\n",FILE_APPEND);
		// p(1);die;
        $info = get_addon_info('epay');
        if(empty($info) || $info['state'] == 0){
            $this->error('请到后台插件管理安装《微信支付宝整合》插件');
        }
		// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----支付3：".json_encode($info)."\n",FILE_APPEND);

        $order_no = $this->request->post('order_no');
        $coupon_id = $this->request->post('coupon_id');
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->where(['order_no'=>$order_no,'user_id'=>$this->auth->id,'pay_status'=>0])->find();
		// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----支付4：".json_encode($postInfo)."\n",FILE_APPEND);
        if($postInfo['type'] == 2&&$postInfo['status']<=3){
             $this->error('当前订单状态还无法支付，请等到全部取件完毕后在支付。');
        }
        if(empty($postInfo)){
            $this->error('当前订单不存在或已支付');
        } 

        // $wechatUser = Third::get(['user_id'=>$this->auth->id]);
        $wechatUser = Db::name('shopro_third_oauth')->where(['user_id'=>$this->auth->id])->find();
		// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----支付5：".json_encode($wechatUser)."\n",FILE_APPEND);
		// if(!$wechatUser)$this->error('获取openId失败，请重新登录');
		if(!$wechatUser)$this->error('微信授权获取失败，请至我的中绑定微信');
		$amount=$postInfo['pay_price'];
		
		if($amount==0){
			$upa=['pay_status'=>1,'coupon_price'=>0,'paytime'=>time(),'updatetime'=>time()];
			if($postInfo['type']==1){
				// $upa['status']=4;
				//目前支付2和4都不需要更改订单状态，只需要更改支付状态2023.11.9
// 			}else{
				$upa['status']=2;
			}
			db('paotui_post')->where('id',$postInfo['id'])->update($upa);
			$this->success('首单免费');
		}
		
		if($postInfo['coupon_price']==0){
			$coupon=Coupon::with('coupon')->where('id', $coupon_id)->canUse()->find();
			// echo json_encode($coupon);
			if($coupon_id){
				if(!$coupon)$this->error('优惠券不可用');
				$cmn=$coupon['amount'];
				
				if($coupon['type']=='discount'){
					$cmn=$amount*$coupon['amount'];
				}
				
				$amount1=$amount-$cmn;
				if($amount1<0)$amount1=0;
				$amount=$amount1;
			}
		}
		// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----支付6：".json_encode($amount)."\n",FILE_APPEND);
		
		$amount=intval($amount * 100)/100;
		$titlewx = '快递代取';
		if($postInfo['type'] == 1){
		    if($postInfo['shopro_order_id'] == 0){
		        $titlewx = '同城跑腿';
		    }else{
		        $titlewx = '商超订单';
		    }
		    
		}
		if($postInfo['type'] == 2){
		    $titlewx = '快递代取';
		}
		if($postInfo['type'] == 5){
		    $titlewx = '洗衣订单';
		}
        $params = [
            'amount'=>$amount,
            'orderid'=>$order_no."_".rand(1000,9999),
            'type'=>"wechat",
            'title'=>$titlewx,//"跑腿订单"
            'notifyurl'=>$this->request->domain()."/api/paotui/block/notifyx",
            'method'=>"miniapp",
            'openid'=>$wechatUser['openid'],
        ];
		// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----支付7：".json_encode($params)."\n",FILE_APPEND);

        $return =  \addons\epay\library\Service::submitOrder($params);
		// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----支付1：".json_encode($return)."\n",FILE_APPEND);
        if($return){
            $this->success('请求成功',json_decode($return));
        }else{
            $this->error("请求失败");
        }



    }
    
    /**
     * 取消订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancel(){
        $order_no = $this->request->post('order_no');

        Db::startTrans();
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->lock(true)->where(['order_no'=>$order_no,'user_id'=>$this->auth->id,'status'=>['in',[0,1,2,3]]])->find();
        if(empty($postInfo)){
            $this->error('当前订单不存在或不可以取消');
        }
        //判断有没有取件
        $code = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id']])->where('take_user_id is not null')->find();
        if($code){
            $this->error('当前订单已取件不可以取消，如需取消请联系客服');
        }
        
        if($postInfo->save(['status'=>-1,'canceltime'=>time()])){

            if($postInfo['pay_price'] >0 ){
                if($postInfo['status'] == 2 || $postInfo['status'] == 3){
                    //退款,原路退回
                    try {
                        $config = \addons\epay\library\Service::getConfig('wechat');

                        $config['app_id'] = $config['miniapp_id'];
                        $pay = Pay::wechat($config);
                        $param = [
                            'transaction_id'=>$postInfo['transaction_id'],
                            'out_refund_no'=>time()."_".rand(1000,9999),
                            'total_fee' => $postInfo['pay_price']*100,
                            'refund_fee'=> $postInfo['pay_price']*100,
                            'refund_desc'=>"退款"
                        ];

                        $result = $pay->refund($param);
                        if($result->result_code == "SUCCESS"){

                            if($postInfo['status'] == 3){
                                //生成socket记录
                                $postSocketModel = new PostSocket();
                                $postSocketInfo = $postSocketModel->where(['post_id'=>$postInfo['id']])->find();
                                if($postSocketInfo){
                                    $postSocketInfo->save(['type'=>4,'poster_id'=>$postInfo['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>time(),'send_status'=>0]);
                                }else{
                                    $postSocketModel = new PostSocket();
                                    $postSocketModel->save(['type'=>4,'post_id'=>$postInfo['id'],'poster_id'=>$postInfo['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>time(),'send_status'=>0]);
                                }
                            }
                            Db::commit();
                            $this->success();
                        }
                    }catch (\Yansongda\Pay\Exceptions\Exception $e){
                        Db::rollback();
                        $this->error("退款申请失败，请联系客服");
                    }
                }else{
                    
                    $pcode = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id']])->update(['canceltime'=>time()]);
                    Db::commit();
                    
                    $this->success();
                }
            }else{
                $pcode = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id']])->update(['canceltime'=>time()]);
                Db::commit();
                $this->success();
            }
        }else{
            Db::rollback();
            $this->error("请求失败");

        }
    }

    /**
     * 删除订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del(){
        $order_no = $this->request->post('order_no');
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->where(['order_no'=>$order_no,'user_id'=>$this->auth->id,'status'=>-1])->find();
        if(empty($postInfo)){
            $this->error('当前订单不存在或不可以删除');
        }
        //取消取件码
        
        if($postInfo->save(['is_delete'=>1,'deletetime'=>time()])){
            $this->success("请求成功");
        }else{
            $this->error("请求失败");

        }
    }
    /**
     * 发送短信
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function send_message($order){
        // 直接发送短信
         $config = get_addon_config('alisms');
        
        $poster = Db::name('paotui_poster')->where(['type'=>1,'is_order'=>1])->select();
        //  p($poster);die;
        foreach($poster as $k=>$v){
            $mobile = $v['mobile'];
            $template = $config['template']['recommand'];
            $sign = '';
            if (!$mobile || !$template) {
                $this->error('手机号、模板ID不能为空');
            }
            $sign = $sign ? $sign : $config['sign'];
            $param = (array)json_decode($this->request->post('param', '', 'trim'));
            // $param['code'] = '1111';
            $alisms = new \addons\alisms\library\Alisms();
            $ret = $alisms->mobile($mobile)
                ->template($template)
                ->sign($sign)
                ->param($param)
                ->send();
           
    	    
    	   if($ret){
    	        Db::name('paotui_post')->where(['order_no'=>$order])->update(['is_send'=>1]);
    	   }else{
    	       $err = $err.','.$v['phone'].' '.$alisms->getError();
    	   }
        }
            
    }
    /**
     * 发送短信 计划任务
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function send_message_task(){
        // 直接发送短信
        if($site['message_button'] == 1){
            $order1 = Db::name('paotui_post')->where(['status'=>2])->where('is_send is null')->select();
        }else{
            $order1 = Db::name('paotui_post')->where(['status'=>2])->where('is_send is null')->where('shopro_order_id',0)->select();
        }
        
        // p($order1);die;
        $order= [];
        foreach($order1 as $k=>$v){
            $code = Db::name('partition_code')->where(['paotui_post_id'=>$v['id']])->where('take_user_id is null')->find();
            
            if($code){
                $order[] = $v;
            }
        }
        // p($order);die;
        if($order){
            $site = Config('site');
            
            $config = get_addon_config('alisms');
            $poster = Db::name('paotui_poster')->where(['type'=>1,'is_order'=>1])->select();
            //  p($poster);die;
            foreach($poster as $k=>$v){
                $mobile = $v['mobile'];
                $template = $config['template']['recommand'];
                $sign = '';
                if (!$mobile || !$template) {
                    $this->error('手机号、模板ID不能为空');
                }
                $sign = $sign ? $sign : $config['sign'];
                $param = (array)json_decode($this->request->post('param', '', 'trim'));
                // $param['code'] = '1111';
                $alisms = new \addons\alisms\library\Alisms();
                $ret = $alisms->mobile($mobile)
                    ->template($template)
                    ->sign($sign)
                    ->param($param)
                    ->send();
               
        	    
        	   if($ret){
        	       //成功群发
        	       foreach($order as $kk=>$vv){
        	           Db::name('paotui_post')->where(['id'=>$vv['id']])->update(['is_send'=>1]);
        	       }
        	   }else{
        	       $err = $err.','.$v['phone'].' '.$alisms->getError();
        	   }
            }
        }    
    }
    
    
    /**
     * 生成跑腿订单
     *
     * @param [type] $order
     * @param [type] $weight
     * @return string
     */
    public function makePaotuiOrder()
    {
        $order_id=$this->request->param('id',1);
        $order =Db::name('shopro_order')->where(['id'=>$order_id])->find();
        $ispaotui=0;
		$order_item=Db::name('shopro_order_item')->where('order_id',$order_id)->select();//不直接用sum是怕以后有什么扩展处理
	
		foreach($order_item as $k=>$v){
			$goods_weight=$v['goods_weight']>0?$v['goods_weight']:1;
			if($v['dispatch_type']=='paotui')$ispaotui+=$goods_weight;
		}
        $weight = $ispaotui;
       
		//只需要这些参数就可以了
		$data['isAddFromPay']=1;
		$data['shopro_order_id'] = $order['id'];
		$data['masks_user_id'] = $order['user_id'];
		$data['user_id'] = $order['user_id'];
		$data['upstairs'] = $order['upstair'];//20240826新增上楼
		$data['type'] = 1;
		$data['from_address_id'] = 1;//我把paotui_order_address的id为1的作为学校地址了
		//获取收货地址
		$address=db('shopro_order_address')->where('order_id',$order['id'])->find();
		$to_address=db('paotui_user_address')->where('user_id',$data['user_id'])->where('shopro_address_id',$address['shopro_address_id'])->order('is_default desc')->find();
		if(!$to_address)$to_address=db('paotui_user_address')->where('user_id',$data['user_id'])->order('is_default desc')->find();
		$data['to_address_id'] = $to_address['id'];//校园跑腿 商品下单时需要设置地址
		
		$gdt=db('paotui_goods_type')->where('id',1)->find();
		$goods_type=$gdt?$gdt['goods_type']:'代拿外卖';
		$data['goods_type'] = $goods_type;
		$data['weight'] = $weight;
			// file_put_contents('./testapi.txt',date('Y-m-d H:i:s')."----订单产品3：".json_encode($data)."\n",FILE_APPEND);
		
		// p($this->user);
		// $data['token']=$this->user->token;
		// Log::write('fasongjparams:' . json_encode($data) );
		//直接执行方法
		// $postController=new \app\api\controller\paotui\Post;
		// return $postController->add($data);
		Http::post('https://www.manchengsh.com/index.php/api/paotui.post/add',$data);
	}
    
    
}
